package com.cat2bug.junit.clazz;

import javassist.*;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.MethodInfo;

/**
 * 复制测试类方法
 */
public class CopyMethodOfTestClass extends AbstractTestClassDecorator {
    private CtMethod method;

    public CopyMethodOfTestClass(ITestClassFactory factory, CtMethod method) {
        super(factory);
        this.method = method;
    }
    @Override
    public CtClass createTestClass(Class<?> clazz) throws Exception {
        CtClass ctClass = super.createTestClass(clazz);
        String methodName = this.method.getName();
        // 拷贝方法
        CtMethod newMethod = CtNewMethod.copy(this.method, methodName, ctClass, null);
        // 获取源方法的注解属性
        MethodInfo sourceMethodInfo = this.method.getMethodInfo();
        AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) sourceMethodInfo.getAttribute(AnnotationsAttribute.visibleTag);

        // 将注解属性添加到复制得到的方法中
        if (annotationsAttribute != null) {
            newMethod.getMethodInfo().addAttribute(annotationsAttribute.copy(newMethod.getMethodInfo().getConstPool(), null));
        }

        ctClass.addMethod(newMethod);


        return ctClass;
    }
}
